package io.github.wx.core.config;

import com.jfinal.aop.Duang;
import com.xiaoleilu.hutool.util.CollectionUtil;
import io.github.wx.common.constant.EnumFuctionStatus;
import io.github.wx.dao.model.SysMenu;
import io.github.wx.dao.model.SysRole;
import io.github.wx.dao.model.SysUser;
import io.github.wx.service.MenuService;
import io.github.wx.service.RoleService;
import io.github.wx.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.util.ByteSource;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by jie on 2017/4/3.
 * 自定义shiro Realm
 */
public class ShiroDbRealm extends AuthorizingRealm {
    static final UserService userService = Duang.duang(UserService.class);
    static final RoleService roleService = Duang.duang(RoleService.class);
    static final MenuService menuService = Duang.duang(MenuService.class);

    /**
     * 认证回调函数,登录时调用.
     *
     * @param authcToken 登录信息集合
     * @return AuthenticationInfo
     * @throws AuthenticationException 认证异常
     */
    protected AuthenticationInfo doGetAuthenticationInfo(
            AuthenticationToken authcToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
        SysUser user = new SysUser();
        user.setUsername(token.getUsername());
        List<SysUser> list = userService.getUserByUsername(user);
        // 账号不存在
        if (CollectionUtil.isEmpty(list))
            throw new UnknownAccountException();//没找到帐号
        SysUser sysUser = list.get(0);
        if (EnumFuctionStatus.BAD_STATUS.getCode().equals(sysUser.getDelFlag()))
            throw new LockedAccountException();
        return new SimpleAuthenticationInfo(sysUser.getUsername(),
                sysUser.getPassword(), ByteSource.Util.bytes(sysUser.getSalt()), getName());
    }


    /**
     * 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用.
     *
     * @param principals 授权信息
     * @return AuthorizationInfo
     */
    protected AuthorizationInfo doGetAuthorizationInfo(
            PrincipalCollection principals) {
        String loginName = (String) principals.fromRealm(getName()).iterator()
                .next();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        SysRole sysRole = roleService.findUserRole(loginName);
        if (null == sysRole) {
            return info;
        }
        info.addRole(sysRole.getRoleName());
        List<SysMenu> menuList = menuService.findByRoleId(sysRole.getRoleId());
        List<String> lists = new ArrayList<String>();
        for (SysMenu menu : menuList) {
            lists.add(menu.getPermission());
        }
        info.addStringPermissions(lists);
        return info;
    }

    /**
     * 更新用户授权信息缓存.
     *
     * @param principal 用户标志
     */
    public void clearCachedAuthorizationInfo(String principal) {
        SimplePrincipalCollection principals = new SimplePrincipalCollection(
                principal, getName());
        clearCachedAuthorizationInfo(principals);
    }

    /**
     * 清除所有用户授权信息缓存.
     */
    public void clearAllCachedAuthorizationInfo() {
        Cache<Object, AuthorizationInfo> cache = getAuthorizationCache();
        if (cache != null) {
            for (Object key : cache.keys()) {
                cache.remove(key);
            }
        }
    }
}